var httpQuest = require('../../request/request.js')
/**
 * 验证手机号码
 */
exports.isPhoneNo = function(tel) {
	var pattern = /^1[345678]\d{9}$/
	return pattern.test(tel)
}

/**
 * 清除前后空格
 */
exports.Trim = function(str) {
	return str.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * 验证身份证
 */
exports.isIdCard = function(code) {
	var city = {
		11: "北京",
		12: "天津",
		13: "河北",
		14: "山西",
		15: "内蒙古",
		21: "辽宁",
		22: "吉林",
		23: "黑龙江 ",
		31: "上海",
		32: "江苏",
		33: "浙江",
		34: "安徽",
		35: "福建",
		36: "江西",
		37: "山东",
		41: "河南",
		42: "湖北 ",
		43: "湖南",
		44: "广东",
		45: "广西",
		46: "海南",
		50: "重庆",
		51: "四川",
		52: "贵州",
		53: "云南",
		54: "西藏 ",
		61: "陕西",
		62: "甘肃",
		63: "青海",
		64: "宁夏",
		65: "新疆",
		71: "台湾",
		81: "香港",
		82: "澳门",
		91: "国外 "
	};
	var tip = "";
	var pass = true;

	if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
		tip = "身份证号格式错误";
		pass = false;
	} else if (!city[code.substr(0, 2)]) {
		tip = "地址编码错误";
		pass = false;
	} else {
		//18位身份证需要验证最后一位校验位
		if (code.length == 18) {
			code = code.split('');
			//∑(ai×Wi)(mod 11)
			//加权因子
			var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
			//校验位
			var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
			var sum = 0;
			var ai = 0;
			var wi = 0;
			for (var i = 0; i < 17; i++) {
				ai = code[i];
				wi = factor[i];
				sum += ai * wi;
			}
			var last = parity[sum % 11];
			if (parity[sum % 11] != code[17]) {
				tip = "校验位错误";
				pass = false;
			}
		}
	}
	return pass;
}


//日期转字符串 返回日期格式20080808
exports.dateToString = function(date) {
	if (date instanceof Date) {
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		month = month < 10 ? '0' + month : month;
		var day = date.getDate();
		day = day < 10 ? '0' + day : day;
		return year + month + day;
	}
	return '';
}

/**
 * 验证姓名
 */
exports.isName = function(str) {
	var pattern = /^[\u4E00-\u9FA5]{2,4}$/
	return pattern.test(str)
}

exports.scancode = function(that) {
	// 允许从相机和相册扫码
	uni.scanCode({
		success: function(res) {
			//console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
			let result = res.result
			// 扫二维码有结果，扫小程序码没结果
			if(res.scanType === 'QR_CODE') {
				if (result.indexOf('/license') > -1) {
					if (result.indexOf('=guest') > -1) {
						uni.navigateTo({
						    url: `/pages/login/index`
						});
					} else if(result.indexOf('=user') > -1) {
						uni.navigateTo({
						    url: `/pages/openWz-step1/index`
						});
					} else if (result.indexOf('=real_user') > -1) {
						uni.navigateTo({
						    url: `/pages/companyAuth/index`
						});
					} else if(result.indexOf('=company_user') > -1) {
						uni.navigateTo({
						    url: `/pages/index/index`
						});
					} else if(result.indexOf('type=separate') > -1) {
						let quertstr = result.split('?')[1]
						uni.navigateTo({
						    url: `/pages/getCertificate/index?${quertstr}`
						});
					} else if(result.indexOf('type=companyAuth') > -1) {
						let quertstr = result.split('?')[1]
						uni.navigateTo({
						    url: `/pages/login/index?${quertstr}`
						});
					} else if(result.indexOf('?company_id=') > -1 || result.indexOf('?scan_flag=') > -1) {
						let quertstr = result.split('?')[1]
						uni.reLaunch({
						    url: `/pages/index/index?${quertstr}`
						});
					} else {
						let strArray = result.split('/')
						let template_id = strArray[strArray.length - 1]
						uni.navigateTo({
						    url: `/pages/applyCertificate/index?template_id=${template_id}`
						});
					}
					return false
				} else {
					if(result.indexOf('http') > -1){
						if(result.indexOf('//employeecard.easyctid') > -1) {
							uni.navigateTo({
								url: `/pages/webview/index?url=${result}`
							}); 
						} else {
							uni.setClipboardData({
								data: result,
								success: function () {
									uni.showToast({
										title: '内容已复制到剪贴板，请到其它浏览器打开',
										duration: 2000,
										icon: 'none'
									});
								}
							});
						}
					} else{
						httpQuest.default.post('/ctid/unity', {
							type: that.$BSNCODE.CODE_AUTHENTICATION
						}, false).then((res2) => {
							that.randomNumber = res2.data.randomNumber
							let param = {
								qrCode: res.result,
								bsn: res2.data.bsn,
								randomNumber: that.randomNumber
							}
							httpQuest.default.post('/ctid/codeAuth', param, true).then((res3) => {
								let storeData = JSON.parse(res3.data.storeData)
								if (!storeData.id) {return false}
								uni.navigateTo({
									url: `/pages/certificateInfo/index?id=${storeData.id}&user_id=${storeData.user_id}`
								});
							}).catch(err => {
						
							})
						}).catch(err => {
						
						})
					}
				}	
			} else if(res.scanType === 'WX_CODE') {
				let queryStr = decodeURIComponent(res.path).split(';')[1]
				uni.reLaunch({
					url: `/pages/index/index?scene=${encodeURIComponent(queryStr)}`
				});
			}
			
		}
	});
}


// 公用的手机授权登录
exports.phoneLogin = function(e, successBack, failBack) {
	if (e.detail.errMsg == 'getPhoneNumber:fail user deny' || e.detail.errMsg == 'getPhoneNumber:fail:user deny') {
		console.log('用户拒绝提供手机号');  
	} else {
		exports.wxlogin().then((r) => {
			let param = {
				encryptedData: e.detail.encryptedData,
				iv: e.detail.iv,
				code: r.code
			}
			exports.postquest(param,successBack, failBack)
		})
	}
}

exports.wxlogin = function(){
	return new Promise((resolve, reject) => {
		uni.login({
			success: function(loginRes) {
				resolve(loginRes)
			}
		})	
	})
}


exports.postquest = function(param, successBack, failBack) {
	httpQuest.default.post('/wechat/register', param, true).then((res) => {
		uni.showToast({
		    title: res.msg,
		    icon: 'none'
		})
		uni.setStorageSync('role', res.role);
		uni.setStorageSync('authorization', res.authorization);
		uni.setStorageSync('phone', res.phone);
		successBack && successBack(res)
		/*if (res.role == 'user') {
			uni.navigateTo({
				url: '/pages/openWz-step1/index'
			});
		} else {
			successBack && successBack(res)
		}*/
		
		httpQuest.default.post('/wechat/userinfo', param, false).then((res2) => {
			uni.setStorageSync('bid', res2.data.bid);
			uni.setStorageSync('user_id', res2.data.userId);
		}).catch(err => {
			
		})
	}).catch(err => {
		failBack && failBack(err)
	})
}

// 截取参数
exports.handlerQuery = function(name, queryStr) {
	if(queryStr == null){
		return null
	}
	let queryList
	if (queryStr.indexOf(',') > -1) {
		queryList = queryStr.split(",")
	} else {
		queryList = [queryStr]
	}
	for(let key of queryList){
		// console.log(key)	//  username=admin    password=admin123
		if(key.split("=")[0] === name){
			return key.split("=")[1]
		}		
	}
}

// 获取正常url的参数
exports.getURLParamInfo = function(name, queryStr) {
	if(queryStr == null){
			return null
		}
	// 以？截取字符串返回一个数组，数组的第一项为？前的数据，数据第2项为？后的数据
	let query = queryStr.split("?")[1]
	let queryList = query.split("&")
	for(let key of queryList){
		if(key.split("=")[0] === name){
			return key.split("=")[1]
		}		
	}
}

// 公用的推送数据
exports.pushData = function(scan_flag) {
	let param = {}
	if(scan_flag) {
		param = {
			scan_flag: scan_flag
		}
	}
	httpQuest.default.post('/user/update_role', param, true).then((res) => {
		if(scan_flag) {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
		uni.setStorageSync('role', res.data.role);
	}).catch((err) => {
		
	})
}

// 判断有没有登录
exports.ifLoginFuc = function() {
	if (!uni.getStorageSync('authorization')) {
		let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
		let curRoute = '/' + routes[routes.length - 1].route
		uni.redirectTo({
			url: `/pages/login/index?rurl=${encodeURIComponent(curRoute)}`
		});
		return false
	}
}